import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import FormInput from '../components/FormInput';
import SubmitButton from '../components/SubmitButton';
import { updatePassword } from '../services/api';

const UpdatePassword: React.FC = () => {
    const navigate = useNavigate();
    const token = localStorage.getItem('token') || '';
    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [error, setError] = useState('');

    const handleUpdate = async () => {
        if (newPassword !== confirmPassword) {
            setError('两次新密码不一致');
            return;
        }
        try {
            await updatePassword(currentPassword, newPassword, confirmPassword, token);
            navigate('/login');
        } catch (err: any) {
            setError(err.response?.data?.error || '修改密码失败');
        }
    };

    return (
        <div className="auth-container">
            <h2>修改密码</h2>
            <p>请输入您的账号信息修改密码</p>
            {error && <p className="error">{error}</p>}
            <FormInput label="当前密码" placeholder="请输入当前密码" type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} />
            <FormInput label="新密码" placeholder="请输入新密码" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
            <FormInput label="确认新密码" placeholder="请确认新密码" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} />
            <SubmitButton text="修改密码" onClick={handleUpdate} />
            <p><a href="#" onClick={() => navigate('/login')}>返回登录</a></p>
        </div>
    );
};

export default UpdatePassword;